<template>
  <van-button
    :icon="isCollected ? 'star' : 'star-o'"
    :class="{ collected: isCollected }"
    :loading='loading'
    @click="onCollect"
  ></van-button>
</template>

<script>
import {addCollect,deleteCollect} from '@/api/article'
export default {
  name: "CollectArticle",
  props: {
    isCollected: {
      type: Boolean,
      required: true
    },
    articleId:{
      type:[Number,String,Object],
      required:true
    }
  },
  model:{
    prop:'isCollected',
    event:'updateCollect'
},
  data() {
    return {
      loading:false
    };
  },
  computed: {},

  created() {},

  mounted() {},

  watch: {},

  methods: {
    async onCollect(){
      this.loading=true
      try {
        if(this.isCollected){
          //已收藏 要取消收藏
          await deleteCollect(this.articleId)
        }else{
          // 没有收藏 要添加收藏
          await addCollect(this.articleId)
        }
        // 更新视图
        // 自定义事件修改数据并不是立即的
        this.$emit('updateCollect', !this.isCollected);
        this.$toast.success(!this.isCollected ? '收藏成功' : '取消收藏')
      } catch (err) {
          console.log(err);
          this.$toast.fail('操作失败，请重试！')
      }
      this.loading=false
    }
  },

  components: {}
};
</script>

<style scoped lang="less">
.collected {
  .van-icon {
    color: #ffa500;
  }
}
</style>
